package com.wonderplay.warlord.engine;

import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;

import com.wonderplay.engine.GameEngine;
import com.wonderplay.engine.LogicEngine;
import com.wonderplay.engine.ModuleChangeMessage;
import com.wonderplay.warlord.conf.WarLordContants;
import com.wonderplay.warlord.module.combat.CharacterCombatStatus;
import com.wonderplay.warlord.module.combat.WarLordCombatLogicEngine;
import com.wonderplay.warlord.module.story.WarLordStoryLogicEngine;

public class WarLordGameEngine extends GameEngine {

	public WarLordGameEngine(Context context) {
		super(context);
		resourceHandler = new WarLordResourceHandler(context);
		currentModule = WarLordContants.MODULE_STORY;

		LogicEngine combatLogicEngine = new WarLordCombatLogicEngine(this,
				WarLordContants.MODULE_COMBAT);
		LogicEngine storyLogicEngine = new WarLordStoryLogicEngine(this,
				WarLordContants.MODULE_STORY);
		registerLogicEngine(WarLordContants.MODULE_STORY, storyLogicEngine);
		registerLogicEngine(WarLordContants.MODULE_COMBAT, combatLogicEngine);
	}

	// how to communicate between logicEngine and displayEngine?
	public void doStep() {
		synchronized (surfaceHolder) {
			moduleEngineMap.get(currentModule).doStep();
		}
	}

	public View getGameView() {
		return displayEngine;
	}

	public SurfaceHolder getSurfaceHolder() {
		return surfaceHolder;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		synchronized (surfaceHolder) {
			moduleEngineMap.get(currentModule).performTouchEvent(event);
		}
		return true;
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		synchronized (surfaceHolder) {
			moduleEngineMap.get(currentModule).performKeyEvent(event);
		}
		return true;
	}

	@Override
	public void onModuleChangeReq(int sendModule, int changeCode,
			ModuleChangeMessage message) {
		synchronized (surfaceHolder) {
			if (sendModule == WarLordContants.MODULE_STORY) {
				WarLordStoryLogicEngine storyEngine = (WarLordStoryLogicEngine) moduleEngineMap
						.get(WarLordContants.MODULE_STORY);

				this.currentModule = changeCode;

				moduleEngineMap.get(sendModule).reset();

				if (this.currentModule == WarLordContants.MODULE_COMBAT) {
					moduleEngineMap.get(this.currentModule).init();

					LogicEngine logicEngine = moduleEngineMap
							.get(this.currentModule);
					if (logicEngine instanceof WarLordCombatLogicEngine) {

						((WarLordCombatLogicEngine) logicEngine)
								.startNewCombat(storyEngine.playerCharStatus,
										storyEngine.opponentCharStatus);

					}
				}
			}else if (sendModule == WarLordContants.MODULE_COMBAT){
				this.currentModule = changeCode;
				moduleEngineMap.get(sendModule).reset();
			}
		}
	}

}
